package com.canyou.service;

import com.canyou.integration.IntegrationAuthentication;
import com.canyou.integration.IntegrationAuthenticationContext;
import com.canyou.integration.IntegrationUserDetails;
import com.canyou.integration.authenticator.IntegrationAuthenticator;
import com.canyou.system.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 集成认证用户服务
 *
 * @author cgz
 * @date 2019-3-7
 **/
@Service
public class IntegrationUserDetailsServiceImpl implements UserDetailsService {

    private List<IntegrationAuthenticator> authenticators;

    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public IntegrationUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        // 判断是否是集成登录
        if (integrationAuthentication == null) {
            integrationAuthentication = new IntegrationAuthentication();
        }
        integrationAuthentication.setUsername(username);
        User user = this.authenticate(integrationAuthentication);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return authorize(user);
    }

    /**
     * User转成IntegrationUserDetails
     *
     * @param user
     * @return
     */
    private IntegrationUserDetails authorize(User user) {
        List<GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;
        boolean enabled = user.getStatus().equals(1);
        return new IntegrationUserDetails(user.getId(), user.getUsername(), user.getPassword(),
                enabled, true, authorities);
    }

    private User authenticate(IntegrationAuthentication integrationAuthentication) {
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return authenticator.authenticate(integrationAuthentication);
                }
            }
        }
        return null;
    }
}